package com.cl.mypureframe.util;

import java.security.MessageDigest;

/**
 * @author zhuchaoxu
 */
public final class UtilMD5 {

    private UtilMD5() {
    }

    private static final String[] h = {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f"};

    public static String MD5Encode(String origin) {
        return MD5Encode(origin, "UTF-8");
    }

    public static String MD5Encode(String origin, String charsetname) {

        String r = null;

        try {

            r = new String(origin);

            MessageDigest m = MessageDigest.getInstance("MD5");

            if (charsetname == null || "".equals(charsetname)) {

                r = byteArrayToHexString(m.digest(r.getBytes()));

            } else {

                r = byteArrayToHexString(m.digest(r.getBytes(charsetname)));

            }

        } catch (Exception exception) {
            exception.printStackTrace();
        }

        return r;

    }

    public static String MD5EncodeCount(String origin, String charsetname, int count) {

        String r = origin;

        for (int i = 0; i < count; i++) {

            r = MD5Encode(r, charsetname);

        }

        return r;

    }

    private static String byteArrayToHexString(byte[] b) {

        StringBuilder r = new StringBuilder();

        for (byte value : b) {

            r.append(byteToHexString(value));

        }

        return r.toString();

    }

    private static String byteToHexString(byte b) {

        int n = b;

        if (n < 0) {

            n += 256;

        }

        int d1 = n / 16;

        int d2 = n % 16;

        return h[d1] + h[d2];

    }

}
